<!-- build time:Tue Dec 17 2019 19:26:41 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="Java,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1"><meta name="description" content="在前面的例子中，我们都是通过new Thread来创建一个线程，由于线程的创建和销毁都需要消耗一定的CPU资源，所以在高并发下这种创建线程的方式将严重影响代码执行效率。而线程池的作用就是让一个线程执行结束后不马上销毁，继续执行新的任务，这样就节省了不断创建线程和销毁线程的开销。"><meta name="keywords" content="Java"><meta property="og:type" content="article"><meta property="og:title" content="深入学习Java线程池"><meta property="og:url" content="http://mrbird.cc/Java-Thread-Pool.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="在前面的例子中，我们都是通过new Thread来创建一个线程，由于线程的创建和销毁都需要消耗一定的CPU资源，所以在高并发下这种创建线程的方式将严重影响代码执行效率。而线程池的作用就是让一个线程执行结束后不马上销毁，继续执行新的任务，这样就节省了不断创建线程和销毁线程的开销。"><meta property="og:locale" content="zh-Hans"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190630215357.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190630222238.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190701183457.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190701184303.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190701185215.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190701185617.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190701190444.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190701190808.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702100110.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702101041.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702101355.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702102156.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190302111014.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702103818.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702105646.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702110022.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702110350.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702152117.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702152440.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190702153306.png"><meta property="og:image" content="http://mrbird.cc/img/20190703205843.png"><meta property="og:image" content="http://mrbird.cc/img/asdfasdfaaaaa.gif"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190703211746.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190703213145.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190704091530.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20190704091836.png"><meta property="og:updated_time" content="2019-10-28T12:14:46.241Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="深入学习Java线程池"><meta name="twitter:description" content="在前面的例子中，我们都是通过new Thread来创建一个线程，由于线程的创建和销毁都需要消耗一定的CPU资源，所以在高并发下这种创建线程的方式将严重影响代码执行效率。而线程池的作用就是让一个线程执行结束后不马上销毁，继续执行新的任务，这样就节省了不断创建线程和销毁线程的开销。"><meta name="twitter:image" content="http://mrbird.cc/img/QQ截图20190630215357.png"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!1},fancybox:!1,motion:!1}</script><title>深入学习Java线程池 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-right:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:1200px}}.header-innerr{position:relative}.header-innerr{padding:20px 0 0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title" style="font-family:Merienda;font-size:1.3rem">MrBird</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section">HOME</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">ARCHIVES</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section">TAGS</a></li><li class="menu-item menu-item-friends"><a href="/friends/" rel="section">FRIENDS</a></li><div class="sidebar-toggle" style="display:none"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"><div class="note info" style="margin:0;letter-spacing:.15px">🐤手把手教你搭建<strong>Spring Cloud微服务权限系统</strong>（从零到部署）：<a style="color:#40dab2;font-weight:600" href="https://www.kancloud.cn/mrbird/spring-cloud" target="_blank">https://www.kancloud.cn/mrbird/spring-cloud</a></div></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/Java-Thread-Pool.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">深入学习Java线程池</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">Posted on</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-20T20:35:35+08:00">2019-03-20 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i>&nbsp;&nbsp;Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><p>在前面的例子中，我们都是通过<code>new Thread</code>来创建一个线程，由于线程的创建和销毁都需要消耗一定的CPU资源，所以在高并发下这种创建线程的方式将严重影响代码执行效率。而线程池的作用就是让一个线程执行结束后不马上销毁，继续执行新的任务，这样就节省了不断创建线程和销毁线程的开销。<a id="more"></a></p><h2 id="ThreadPoolExecutor"><a href="#ThreadPoolExecutor" class="headerlink" title="ThreadPoolExecutor"></a>ThreadPoolExecutor</h2><p>创建Java线程池最为核心的类为<code>ThreadPoolExecutor</code>：</p><p><img src="img/QQ截图20190630215357.png" alt="QQ截图20190630215357.png"></p><p>它提供了四种构造函数来创建线程池，其中最为核心的构造函数如下所示：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize,</span></span></span><br><span class="line"><span class="function"><span class="params">                              <span class="keyword">int</span> maximumPoolSize,</span></span></span><br><span class="line"><span class="function"><span class="params">                              <span class="keyword">long</span> keepAliveTime,</span></span></span><br><span class="line"><span class="function"><span class="params">                              TimeUnit unit,</span></span></span><br><span class="line"><span class="function"><span class="params">                              BlockingQueue&lt;Runnable&gt; workQueue,</span></span></span><br><span class="line"><span class="function"><span class="params">                              ThreadFactory threadFactory,</span></span></span><br><span class="line"><span class="function"><span class="params">                              RejectedExecutionHandler handler)</span></span></span><br></pre></td></tr></table></figure><p></p><p>这7个参数的含义如下：</p><ol><li><p><strong>corePoolSize</strong> 线程池核心线程数。即线程池中保留的线程个数，即使这些线程是空闲的，也不会被销毁，除非通过ThreadPoolExecutor的<code>allowCoreThreadTimeOut(true)</code>方法开启了核心线程的超时策略；</p></li><li><p><strong>maximumPoolSize</strong> 线程池中允许的最大线程个数；</p></li><li><p><strong>keepAliveTime</strong> 用于设置那些超出核心线程数量的线程的最大等待时间，超过这个时间还没有新任务的话，超出的线程将被销毁；</p></li><li><p><strong>unit</strong> 超时时间单位；</p></li><li><p><strong>workQueue</strong> 线程队列。用于保存通过execute方法提交的，等待被执行的任务；</p></li><li><p><strong>threadFactory</strong> 线程创建工程，即指定怎样创建线程；</p></li><li><p><strong>handler</strong> 拒绝策略。即指定当线程提交的数量超出了maximumPoolSize后，该使用什么策略处理超出的线程。</p></li></ol><p>在通过这个构造方法创建线程池的时候，这几个参数必须满足以下条件，否则将抛出<code>IllegalArgumentException</code>异常：</p><ol><li><p>corePoolSize不能小于0；</p></li><li><p>keepAliveTime不能小于0；</p></li><li><p>maximumPoolSize 不能小于等于0；</p></li><li><p>maximumPoolSize不能小于corePoolSize；</p></li></ol><p>此外，workQueue、threadFactory和handler不能为null，否则将抛出空指针异常。</p><p>下面举些例子来深入理解这几个参数的含义。</p><p>使用上面的构造方法创建一个线程池：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">                <span class="number">1</span>, <span class="number">2</span>, <span class="number">10</span>,</span><br><span class="line">                TimeUnit.SECONDS,</span><br><span class="line">                <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">                <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">System.out.println(<span class="string">"线程池创建完毕"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> activeCount = -<span class="number">1</span>;</span><br><span class="line"><span class="keyword">int</span> queueSize = -<span class="number">1</span>;</span><br><span class="line"><span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (activeCount != threadPoolExecutor.getActiveCount()</span><br><span class="line">            || queueSize != threadPoolExecutor.getQueue().size()) &#123;</span><br><span class="line">        System.out.println(<span class="string">"活跃线程个数 "</span> + threadPoolExecutor.getActiveCount());</span><br><span class="line">        System.out.println(<span class="string">"核心线程个数 "</span> + threadPoolExecutor.getCorePoolSize());</span><br><span class="line">        System.out.println(<span class="string">"队列线程个数 "</span> + threadPoolExecutor.getQueue().size());</span><br><span class="line">        System.out.println(<span class="string">"最大线程数 "</span> + threadPoolExecutor.getMaximumPoolSize());</span><br><span class="line">        System.out.println(<span class="string">"------------------------------------"</span>);</span><br><span class="line">        activeCount = threadPoolExecutor.getActiveCount();</span><br><span class="line">        queueSize = threadPoolExecutor.getQueue().size();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>上面的代码创建了一个核心线程数量为1，允许最大线程数量为2，最大活跃时间为10秒，线程队列长度为1的线程池。</p><p>假如我们通过execute方法向线程池提交1个任务，看看结果如何：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">                <span class="number">1</span>, <span class="number">2</span>, <span class="number">10</span>,</span><br><span class="line">                TimeUnit.SECONDS,</span><br><span class="line">                <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">                <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">System.out.println(<span class="string">"线程池创建完毕"</span>);</span><br><span class="line"></span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> activeCount = -<span class="number">1</span>;</span><br><span class="line"><span class="keyword">int</span> queueSize = -<span class="number">1</span>;</span><br><span class="line"><span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (activeCount != threadPoolExecutor.getActiveCount()</span><br><span class="line">            || queueSize != threadPoolExecutor.getQueue().size()) &#123;</span><br><span class="line">        System.out.println(<span class="string">"活跃线程个数 "</span> + threadPoolExecutor.getActiveCount());</span><br><span class="line">        System.out.println(<span class="string">"核心线程个数 "</span> + threadPoolExecutor.getCorePoolSize());</span><br><span class="line">        System.out.println(<span class="string">"队列线程个数 "</span> + threadPoolExecutor.getQueue().size());</span><br><span class="line">        System.out.println(<span class="string">"最大线程数 "</span> + threadPoolExecutor.getMaximumPoolSize());</span><br><span class="line">        System.out.println(<span class="string">"------------------------------------"</span>);</span><br><span class="line">        activeCount = threadPoolExecutor.getActiveCount();</span><br><span class="line">        queueSize = threadPoolExecutor.getQueue().size();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><div class="note info"><p>ThreadPoolExecutor的execute和submit方法都可以向线程池提交任务，区别是，submit方法能够返回执行结果，返回值类型为Future</p></div><p>sleep方法代码：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sleep</span><span class="params">(<span class="keyword">long</span> value)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName() + <span class="string">"线程执行sleep方法"</span>);</span><br><span class="line">        TimeUnit.SECONDS.sleep(value);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>启动程序，控制台输出如下： <img src="img/QQ截图20190630222238.png" alt="QQ截图20190630222238.png"></p><p>线程池核心线程数量为1，通过execute提交了一个任务后，由于核心线程是空闲的，所以任务被执行了。由于这个任务的逻辑是休眠100秒，所以在这100秒内，线程池的活跃线程数量为1。此外，因为提交的任务被核心线程执行了，所以并没有线程需要被放到线程队列里等待，线程队列长度为0。</p><p>假如我们通过execute方法向线程池提交2个任务，看看结果如何：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br></pre></td></tr></table></figure><p></p><p><img src="img/QQ截图20190701183457.png" alt="QQ截图20190701183457.png"></p><p>线程池核心线程数量为1，通过execute提交了2个任务后，一开始核心线程是空闲的，Thread-0被执行。由于这个任务的逻辑是休眠100秒，所以在这100秒内，线程池的活跃线程数量为1。因为核心线程数量为1，所以另外一个任务在这100秒内不能被执行，于是被放到线程队列里等待，线程队列长度为1。</p><p>假如我们通过execute方法向线程池提交3个任务，看看结果如何：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br></pre></td></tr></table></figure><p></p><p><img src="img/QQ截图20190701184303.png" alt="QQ截图20190701184303.png"></p><p>这三个任务都是休眠100秒，所以核心线程池中第一个任务正在被执行，第二个任务被放入到了线程队列。而当第三个任务被提交进来时，线程队列满了（我们定义的长度为1），由于该线程池允许的最大线程数量为2，所以线程池还可以再创建一个线程来执行另外一个任务，于是乎之前在线程队列里的线程被取出执行（FIFO），第三个任务被放入到了线程队列。</p><p>改变第二个和第三个任务的睡眠时间，观察输出：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">5</span>));</span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">5</span>));</span><br></pre></td></tr></table></figure><p></p><p><img src="img/QQ截图20190701185215.png" alt="QQ截图20190701185215.png"></p><p>第二个任务提交5秒后，任务执行完毕，所以线程队列里的任务被执行，于是队列线程个数为0，活跃线程数量为2（第一个和第三个任务）。再过5秒后，第三个任务执行完毕，于是活跃线程数量为1（第一个100秒还没执行完毕）。</p><p>在第三个任务结束的瞬间，我们观察线程快照:</p><p><img src="img/QQ截图20190701185617.png" alt="QQ截图20190701185617.png"></p><p>可以看到，线程池中有两个线程，Thread-0在执行第一个任务（休眠100秒，还没结束），Thread-1执行完第三个任务后并没有马上被销毁。过段时间后（10秒钟后）再观察线程快照:</p><p><img src="img/QQ截图20190701190444.png" alt="QQ截图20190701190444.png"></p><p>可以看到，Thread-1这个线程被销毁了，因为我们在创建线程池的时候，指定keepAliveTime 为10秒，10秒后，超出核心线程池线程外的那些线程将被销毁。</p><p>假如一次性提交4个任务，看看会怎样：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br><span class="line">threadPoolExecutor.execute(() -&gt; sleep(<span class="number">100</span>));</span><br></pre></td></tr></table></figure><p></p><p><img src="img/QQ截图20190701190808.png" alt="QQ截图20190701190808.png"></p><p>因为我们设置的拒绝策略为AbortPolicy，所以最后提交的那个任务直接被拒绝了。更多拒绝策略下面会介绍到。</p><h2 id="关闭线程池"><a href="#关闭线程池" class="headerlink" title="关闭线程池"></a>关闭线程池</h2><p>线程池包含以下几个状态：</p><p><img src="img/QQ截图20190702100110.png" alt="QQ截图20190702100110.png"></p><p>当线程池中所有任务都处理完毕后，线程并不会自己关闭。我们可以通过调用<code>shutdown</code>和<code>shutdownNow</code>方法来关闭线程池。两者的区别在于：</p><ol><li><p><code>shutdown</code>方法将线程池置为shutdown状态，拒绝新的任务提交，但线程池并不会马上关闭，而是等待所有正在折行的和线程队列里的任务都执行完毕后，线程池才会被关闭。所以这个方法是平滑的关闭线程池。</p></li><li><p><code>shutdownNow</code>方法将线程池置为stop状态，拒绝新的任务提交，中断正在执行的那些任务，并且清除线程队列里的任务并返回。所以这个方法是比较“暴力”的。</p></li></ol><p>举两个例子观察下两者的区别：</p><p><code>shutdown</code>例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">4</span>, <span class="number">10</span>,</span><br><span class="line">            TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">2</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask());</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.shutdown();</span><br><span class="line">    System.out.println(<span class="string">"已经执行了线程池shutdown方法"</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">shortTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行shortTask完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"shortTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">longTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行longTask完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"longTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>启动程序，控制台输出如下：</p><p><img src="img/QQ截图20190702101041.png" alt="QQ截图20190702101041.png"></p><p>可以看到，虽然在任务都被提交后马上执行了<code>shutdown</code>方法，但是并不会马上关闭线程池，而是等待所有被提交的任务都执行完了才关闭。</p><p><code>shutdownNow</code>例子：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">4</span>, <span class="number">10</span>,</span><br><span class="line">            TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">2</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask());</span><br><span class="line"></span><br><span class="line">    List&lt;Runnable&gt; runnables = threadPoolExecutor.shutdownNow(); <span class="comment">// 马上关闭，并返回还未被执行的任务</span></span><br><span class="line">    System.out.println(runnables);</span><br><span class="line"></span><br><span class="line">    System.out.println(<span class="string">"已经执行了线程池shutdownNow方法"</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">shortTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行shortTask完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"shortTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">longTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行longTask完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"longTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>启动程序，控制台输出如下： <img src="img/QQ截图20190702101355.png" alt="QQ截图20190702101355.png"></p><p>可以看到，在执行<code>shutdownNow</code>方法后，线程池马上就被关闭了，正在执行中的两个任务被打断，并且返回了线程队列中等待被执行的两个任务。</p><p>通过上面两个例子我们还可以看到<code>shutdown</code>和<code>shutdownNow</code>方法都不是阻塞的。常与<code>shutdown</code>搭配的方法有<code>awaitTermination</code>。</p><p><code>awaitTermination</code>方法接收timeout和TimeUnit两个参数，用于设定超时时间及单位。当等待超过设定时间时，会监测ExecutorService是否已经关闭，若关闭则返回true，否则返回false。该方法是阻塞的：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">4</span>, <span class="number">10</span>,</span><br><span class="line">            TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">2</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask());</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask());</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.shutdown();</span><br><span class="line">    <span class="keyword">boolean</span> isShutdown = threadPoolExecutor.awaitTermination(<span class="number">3</span>, TimeUnit.SECONDS);</span><br><span class="line">    <span class="keyword">if</span> (isShutdown) &#123;</span><br><span class="line">        System.out.println(<span class="string">"线程池在3秒内成功关闭"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">"等了3秒还没关闭，不等了╰（‵□′）╯"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(<span class="string">"------------"</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">shortTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行shortTask完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"shortTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">longTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行longTask完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"longTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>启动程序输出如下：</p><p><img src="img/QQ截图20190702102156.png" alt="QQ截图20190702102156.png"></p><h2 id="4大拒绝策略"><a href="#4大拒绝策略" class="headerlink" title="4大拒绝策略"></a>4大拒绝策略</h2><p>当线程池无法再接收新的任务的时候，可采取如下四种策略： <img src="img/QQ截图20190302111014.png" alt="QQ截图20190302111014.png"></p><h3 id="CallerRunsPolicy"><a href="#CallerRunsPolicy" class="headerlink" title="CallerRunsPolicy"></a>CallerRunsPolicy</h3><p><code>CallerRunsPolicy</code>策略：由调用线程处理该任务：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">3</span>, <span class="number">10</span>,</span><br><span class="line">            TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.CallerRunsPolicy());</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务1"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask(<span class="string">"任务2"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask(<span class="string">"任务3"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务4"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务5"</span>));</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.shutdown();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">shortTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">shortTask</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行shortTask-name-"</span> + name + <span class="string">"完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"shortTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">longTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">longTask</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行longTask-name-"</span> + name + <span class="string">"完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"longTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>上面的线程池最多只能一次性提交4个任务，第5个任务提交后会被拒绝策略处理。启动程序输出如下：</p><p><img src="img/QQ截图20190702103818.png" alt="QQ截图20190702103818.png"></p><p>可以看到，第5个提交的任务由调用线程（即main线程）处理该任务。</p><h3 id="AbortPolicy"><a href="#AbortPolicy" class="headerlink" title="AbortPolicy"></a>AbortPolicy</h3><p><code>AbortPolicy</code>策略：丢弃任务，并抛出<code>RejectedExecutionException</code>异常。前面的例子就是使用该策略，所以不再演示。</p><h3 id="DiscardOldestPolicy"><a href="#DiscardOldestPolicy" class="headerlink" title="DiscardOldestPolicy"></a>DiscardOldestPolicy</h3><p><code>DiscardOldestPolicy</code>策略：丢弃最早被放入到线程队列的任务，将新提交的任务放入到线程队列末端：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">3</span>, <span class="number">10</span>,</span><br><span class="line">            TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.DiscardOldestPolicy());</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务1"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask(<span class="string">"任务2"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask(<span class="string">"任务3"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务4"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务5"</span>));</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.shutdown();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">shortTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">shortTask</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行shortTask-name-"</span> + name + <span class="string">"完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"shortTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">longTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">longTask</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行longTask-name-"</span> + name + <span class="string">"完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"longTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>启动程序输出如下：</p><p><img src="img/QQ截图20190702105646.png" alt="QQ截图20190702105646.png"></p><p>可以看到最后提交的任务被执行了，而第3个任务是第一个被放到线程队列的任务，被丢弃了。</p><h3 id="DiscardPolicy"><a href="#DiscardPolicy" class="headerlink" title="DiscardPolicy"></a>DiscardPolicy</h3><p><code>DiscardPolicy</code>策略：直接丢弃新的任务，不抛异常：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">3</span>, <span class="number">10</span>,</span><br><span class="line">            TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.DiscardPolicy());</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务1"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask(<span class="string">"任务2"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> longTask(<span class="string">"任务3"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务4"</span>));</span><br><span class="line">    threadPoolExecutor.execute(<span class="keyword">new</span> shortTask(<span class="string">"任务5"</span>));</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.shutdown();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">shortTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">shortTask</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行shortTask-name-"</span> + name + <span class="string">"完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"shortTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">longTask</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">longTask</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"执行longTask-name-"</span> + name + <span class="string">"完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            System.err.println(<span class="string">"longTask执行过程中被打断"</span> + e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>启动程序，输出如下： <img src="img/QQ截图20190702110022.png" alt="QQ截图20190702110022.png"></p><p>第5个任务直接被拒绝丢弃了，而没有抛出任何异常。</p><h2 id="线程池工厂方法"><a href="#线程池工厂方法" class="headerlink" title="线程池工厂方法"></a>线程池工厂方法</h2><p>除了使用ThreadPoolExecutor的构造方法创建线程池外，我们也可以使用<code>Executors</code>提供的工厂方法来创建不同类型的线程池：</p><p><img src="img/QQ截图20190702110350.png" alt="QQ截图20190702110350.png"></p><h3 id="newFixedThreadPool"><a href="#newFixedThreadPool" class="headerlink" title="newFixedThreadPool"></a>newFixedThreadPool</h3><p>查看<code>newFixedThreadPool</code>方法源码：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExecutorService <span class="title">newFixedThreadPool</span><span class="params">(<span class="keyword">int</span> nThreads)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(nThreads, nThreads,</span><br><span class="line">                                  <span class="number">0L</span>, TimeUnit.MILLISECONDS,</span><br><span class="line">                                  <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>可以看到，通过<code>newFixedThreadPool</code>创建的是一个固定大小的线程池，大小由<code>nThreads</code>参数指定，它具有如下几个特点:</p><ol><li><p>因为corePoolSize和maximumPoolSize的值都为nThreads，所以线程池中线程数量永远等于nThreads，不可能新建除了核心线程数的线程来处理任务，即keepAliveTime实际上在这里是无效的。</p></li><li><p>LinkedBlockingQueue是一个无界队列（最大长度为Integer.MAX_VALUE），所以这个线程池理论是可以无限的接收新的任务，这就是为什么上面没有指定拒绝策略的原因。</p></li></ol><h3 id="newCachedThreadPool"><a href="#newCachedThreadPool" class="headerlink" title="newCachedThreadPool"></a>newCachedThreadPool</h3><p>查看<code>newCachedThreadPool</code>方法源码：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExecutorService <span class="title">newCachedThreadPool</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">0</span>, Integer.MAX_VALUE,</span><br><span class="line">                                  <span class="number">60L</span>, TimeUnit.SECONDS,</span><br><span class="line">                                  <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>这是一个理论上无限大小的线程池：</p><ol><li><p>核心线程数为0，SynchronousQueue队列是没有长度的队列，所以当有新的任务提交，如果有空闲的还未超时的（最大空闲时间60秒）线程则执行该任务，否则新增一个线程来处理该任务。</p></li><li><p>因为线程数量没有限制，理论上可以接收无限个新任务，所以这里也没有指定拒绝策略。</p></li></ol><h3 id="newSingleThreadExecutor"><a href="#newSingleThreadExecutor" class="headerlink" title="newSingleThreadExecutor"></a>newSingleThreadExecutor</h3><p>查看<code>newSingleThreadExecutor</code>源码：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExecutorService <span class="title">newSingleThreadExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> FinalizableDelegatedExecutorService</span><br><span class="line">        (<span class="keyword">new</span> ThreadPoolExecutor(<span class="number">1</span>, <span class="number">1</span>,</span><br><span class="line">                                <span class="number">0L</span>, TimeUnit.MILLISECONDS,</span><br><span class="line">                                <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><ol><li><p>核心线程数和最大线程数都为1，每次只能有一个线程处理任务。</p></li><li><p>LinkedBlockingQueue队列可以接收无限个新任务。</p></li></ol><h3 id="newScheduledThreadPool"><a href="#newScheduledThreadPool" class="headerlink" title="newScheduledThreadPool"></a>newScheduledThreadPool</h3><p>查看<code>newScheduledThreadPool</code>源码：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ScheduledExecutorService <span class="title">newScheduledThreadPool</span><span class="params">(<span class="keyword">int</span> corePoolSize)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ScheduledThreadPoolExecutor(corePoolSize);</span><br><span class="line">&#125;</span><br><span class="line">......</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ScheduledThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(corePoolSize, Integer.MAX_VALUE, <span class="number">0</span>, NANOSECONDS,</span><br><span class="line">          <span class="keyword">new</span> DelayedWorkQueue());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>所以<code>newScheduledThreadPool</code>理论是也是可以接收无限个任务，DelayedWorkQueue也是一个无界队列。</p><p>使用newScheduledThreadPool创建的线程池除了可以处理普通的Runnable任务外，它还具有调度的功能：</p><p>1.延迟指定时间后执行：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ScheduledExecutorService executorService = Executors.newScheduledThreadPool(<span class="number">1</span>);</span><br><span class="line"><span class="comment">// 延迟5秒执行</span></span><br><span class="line">executorService.schedule(() -&gt; System.out.println(<span class="string">"hello"</span>), <span class="number">5</span>, TimeUnit.SECONDS);</span><br></pre></td></tr></table></figure><p></p><p>2.按指定的速率执行：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ScheduledExecutorService executorService = Executors.newScheduledThreadPool(<span class="number">1</span>);</span><br><span class="line"><span class="comment">// 延迟1秒执行，然后每5秒执行一次</span></span><br><span class="line">executorService.scheduleAtFixedRate(</span><br><span class="line">        () -&gt; System.out.println(LocalTime.now()), <span class="number">1</span>, <span class="number">5</span>, TimeUnit.SECONDS</span><br><span class="line">);</span><br></pre></td></tr></table></figure><p></p><p><img src="img/QQ截图20190702152117.png" alt="QQ截图20190702152117.png"></p><p>3.按指定的时延执行：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ScheduledExecutorService executorService = Executors.newScheduledThreadPool(<span class="number">1</span>);</span><br><span class="line">executorService.scheduleWithFixedDelay(</span><br><span class="line">        () -&gt; System.out.println(LocalTime.now()), <span class="number">1</span>, <span class="number">5</span>, TimeUnit.SECONDS</span><br><span class="line">);</span><br></pre></td></tr></table></figure><p></p><p><img src="img/QQ截图20190702152440.png" alt="QQ截图20190702152440.png"></p><p>乍一看，scheduleAtFixedRate和scheduleWithFixedDelay没啥区别，实际它们还是有区别的：</p><ul><li><p>scheduleAtFixedRate按照固定速率执行任务，比如每5秒执行一个任务，即使上一个任务没有结束，5秒后也会开始处理新的任务；</p></li><li><p>scheduleWithFixedDelay按照固定的时延处理任务，比如每延迟5秒执行一个任务，无论上一个任务处理了1秒，1分钟还是1小时，下一个任务总是在上一个任务执行完毕后5秒钟后开始执行。</p></li></ul><p>对于这些线程池工厂方法的使用，阿里巴巴编程规程指出：</p><p><img src="img/QQ截图20190702153306.png" alt="QQ截图20190702153306.png"></p><p>因为这几个线程池理论是都可以接收无限个任务，所以这就有内存溢出的风险。实际上只要我们掌握了ThreadPoolExecutor构造函数7个参数的含义，我们就可以根据不同的业务来创建出符合需求的线程池。一般线程池的创建可以参考如下规则：</p><ul><li><p>IO密集型任务，线程池线程数量可以设置为2 X CPU核心数；</p></li><li><p>计算密集型任务，线程池线程数量可以设置为CPU核心数 + 1。</p></li></ul><h2 id="一些API的用法"><a href="#一些API的用法" class="headerlink" title="一些API的用法"></a>一些API的用法</h2><p>ThreadPoolExecutor提供了几个判断线程池状态的方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">1</span>, <span class="number">2</span>, <span class="number">5</span>, TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy()</span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.execute(() -&gt; &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.shutdown();</span><br><span class="line">    System.out.println(<span class="string">"线程池为shutdown状态："</span> + threadPoolExecutor.isShutdown());</span><br><span class="line">    System.out.println(<span class="string">"线程池正在关闭："</span> + threadPoolExecutor.isTerminating());</span><br><span class="line">    System.out.println(<span class="string">"线程池已经关闭："</span> + threadPoolExecutor.isTerminated());</span><br><span class="line">    threadPoolExecutor.awaitTermination(<span class="number">6</span>, TimeUnit.SECONDS);</span><br><span class="line">    System.out.println(<span class="string">"线程池已经关闭"</span> + threadPoolExecutor.isTerminated());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>程序输出如下：</p><p><img src="img/20190703205843.png" alt="20190703205843.png"></p><p>前面我们提到，线程池核心线程即使是空闲状态也不会被销毁，除非使用<code>allowCoreThreadTimeOut</code>设置了允许核心线程超时：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">       ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">               <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, TimeUnit.SECONDS,</span><br><span class="line">               <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">               <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy()</span><br><span class="line">       );</span><br><span class="line">       threadPoolExecutor.allowCoreThreadTimeOut(<span class="keyword">true</span>);</span><br><span class="line">       threadPoolExecutor.execute(() -&gt; &#123;</span><br><span class="line">           <span class="keyword">try</span> &#123;</span><br><span class="line">               TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">               System.out.println(<span class="string">"任务执行完毕"</span>);</span><br><span class="line">           &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">               e.printStackTrace();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure><p></p><p>程序输出如下所示：</p><p><img src="img/asdfasdfaaaaa.gif" alt="asdfasdfaaaaa.gif"></p><p>5秒后任务执行完毕，核心线程处于空闲的状态。因为通过<code>allowCoreThreadTimeOut</code>方法设置了允许核心线程超时，所以3秒后（keepAliveTime设置为3秒），核心线程被销毁。核心线程被销毁后，线程池也就没有作用了，于是就自动关闭了。</p><div class="note danger"><p>值得注意的是，如果一个线程池调用了<code>allowCoreThreadTimeOut(true)</code>方法，那么它的<code>keepAliveTime</code>不能为0。</p></div><p>ThreadPoolExecutor提供了一<code>remove</code>方法，查看其源码：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">remove</span><span class="params">(Runnable task)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">boolean</span> removed = workQueue.remove(task);</span><br><span class="line">    tryTerminate(); <span class="comment">// In case SHUTDOWN and now empty</span></span><br><span class="line">    <span class="keyword">return</span> removed;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>可看到，它删除的是线程队列中的任务，而非正在被执行的任务。举个例子：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy()</span><br><span class="line">    );</span><br><span class="line">    threadPoolExecutor.execute(() -&gt; &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">5</span>);</span><br><span class="line">            System.out.println(<span class="string">"任务执行完毕"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    Runnable r = () -&gt; System.out.println(<span class="string">"看看我是否会被删除"</span>);</span><br><span class="line">    threadPoolExecutor.execute(r);</span><br><span class="line">    threadPoolExecutor.remove(r);</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.shutdown();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>执行程序，输出如下：</p><p><img src="img/QQ截图20190703211746.png" alt="QQ截图20190703211746.png"></p><p>可看到任务并没有被执行，已经被删除，因为唯一一个核心线程已经在执行任务了，所以后提交的这个任务被放到了线程队列里，然后通过remove方法删除。</p><p>默认情况下，只有当往线程池里提交了任务后，线程池才会启动核心线程处理任务。我们可以通过调用<code>prestartCoreThread</code>方法，让核心线程即使没有任务提交，也处于等待执行任务的活跃状态：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>, TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy()</span><br><span class="line">    );</span><br><span class="line">    System.out.println(<span class="string">"活跃线程数: "</span> + threadPoolExecutor.getActiveCount());</span><br><span class="line">    threadPoolExecutor.prestartCoreThread();</span><br><span class="line">    System.out.println(<span class="string">"活跃线程数: "</span> + threadPoolExecutor.getActiveCount());</span><br><span class="line">    threadPoolExecutor.prestartCoreThread();</span><br><span class="line">    System.out.println(<span class="string">"活跃线程数: "</span> + threadPoolExecutor.getActiveCount());</span><br><span class="line">    threadPoolExecutor.prestartCoreThread();</span><br><span class="line">    System.out.println(<span class="string">"活跃线程数: "</span> + threadPoolExecutor.getActiveCount());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>程序输出如下所示：</p><p><img src="img/QQ截图20190703213145.png" alt="QQ截图20190703213145.png"></p><p>该方法返回boolean类型值，如果所以核心线程都启动了，返回false，反之返回true。</p><p>还有一个和它类似的<code>prestartAllCoreThreads</code>方法，它的作用是一次性启动所有核心线程，让其处于活跃地等待执行任务的状态。</p><p>ThreadPoolExecutor的invokeAny方法用于随机执行任务集合中的某个任务，并返回执行结果，该方法是同步方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException, ExecutionException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">5</span>, <span class="number">3</span>, TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy()</span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 任务集合</span></span><br><span class="line">    List&lt;Callable&lt;Integer&gt;&gt; tasks = IntStream.range(<span class="number">0</span>, <span class="number">4</span>).boxed().map(i -&gt; (Callable&lt;Integer&gt;) () -&gt; &#123;</span><br><span class="line">        TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(<span class="number">5</span>));</span><br><span class="line">        <span class="keyword">return</span> i;</span><br><span class="line">    &#125;).collect(Collectors.toList());</span><br><span class="line">    <span class="comment">// 随机执行结果</span></span><br><span class="line">    Integer result = threadPoolExecutor.invokeAny(tasks);</span><br><span class="line">    System.out.println(<span class="string">"-------------------"</span>);</span><br><span class="line">    System.out.println(result);</span><br><span class="line">    threadPoolExecutor.shutdownNow();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>启动程序，输出如下：</p><p><img src="img/QQ截图20190704091530.png" alt="QQ截图20190704091530.png"></p><p>ThreadPoolExecutor的invokeAll则是执行任务集合中的所有任务，返回Future集合：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException, ExecutionException </span>&#123;</span><br><span class="line">    ThreadPoolExecutor threadPoolExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">            <span class="number">2</span>, <span class="number">5</span>, <span class="number">3</span>, TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">1</span>), (ThreadFactory) Thread::<span class="keyword">new</span>,</span><br><span class="line">            <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy()</span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    List&lt;Callable&lt;Integer&gt;&gt; tasks = IntStream.range(<span class="number">0</span>, <span class="number">4</span>).boxed().map(i -&gt; (Callable&lt;Integer&gt;) () -&gt; &#123;</span><br><span class="line">        TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(<span class="number">5</span>));</span><br><span class="line">        <span class="keyword">return</span> i;</span><br><span class="line">    &#125;).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">    List&lt;Future&lt;Integer&gt;&gt; futureList = threadPoolExecutor.invokeAll(tasks);</span><br><span class="line">    futureList.stream().map(f-&gt;&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> f.get();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException | ExecutionException e) &#123;</span><br><span class="line">           <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).forEach(System.out::println);</span><br><span class="line"></span><br><span class="line">    threadPoolExecutor.shutdownNow();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>输出如下： <img src="img/QQ截图20190704091836.png" alt="QQ截图20190704091836.png"></p><p>总结下这些方法：</p><table><tr><th>方法</th><th>描述</th></tr><tr><td>allowCoreThreadTimeOut(boolean value)</td><td>是否允许核心线程空闲后超时，是的话超时后核心线程将销毁，线程池自动关闭</td></tr><tr><td>awaitTermination(long timeout, TimeUnit unit)</td><td>阻塞当前线程，等待线程池关闭，timeout用于指定等待时间。</td></tr><tr><td>execute(Runnable command)</td><td>向线程池提交任务，没有返回值</td></tr><tr><td>submit(Runnable task)</td><td>向线程池提交任务，返回Future</td></tr><tr><td>isShutdown()</td><td>判断线程池是否为shutdown状态</td></tr><tr><td>isTerminating()</td><td>判断线程池是否正在关闭</td></tr><tr><td>isTerminated()</td><td>判断线程池是否已经关闭</td></tr><tr><td>remove(Runnable task)</td><td>移除线程队列中的指定任务</td></tr><tr><td>prestartCoreThread()</td><td>提前让一个核心线程处于活跃状态，等待执行任务</td></tr><tr><td>prestartAllCoreThreads()</td><td>提前让所有核心线程处于活跃状态，等待执行任务</td></tr><tr><td>getActiveCount()</td><td>获取线程池活跃线程数</td></tr><tr><td>getCorePoolSize()</td><td>获取线程池核心线程数</td></tr><tr><td>threadPoolExecutor.getQueue()</td><td>获取线程池线程队列</td></tr><tr><td>getMaximumPoolSize()</td><td>获取线程池最大线程数</td></tr><tr><td>shutdown()</td><td>让线程池处于shutdown状态，不再接收任务，等待所有正在运行中的任务结束后，关闭线程池。</td></tr><tr><td>shutdownNow()</td><td>让线程池处于stop状态，不再接受任务，尝试打断正在运行中的任务，并关闭线程池，返回线程队列中的任务。</td></tr></table><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787"><div>请作者喝瓶肥宅水~</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">￥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="http://mrbird.cc/Java-Thread-Pool.html" title="深入学习Java线程池">http://mrbird.cc/Java-Thread-Pool.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/Java/" rel="tag"># Java</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/Java-Concurrency-Lock.html" rel="next" title="Java Concurrency Lock"><i class="fa fa-chevron-left"></i> Java Concurrency Lock</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/JDK7-Fork-Join.html" rel="prev" title="Fork/Join使用学习">Fork/Join使用学习 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#42b983!important}.valine .vinfo .col{text-align:left;margin-left:-27rem}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#42b983}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#42b983;border-color:#42b983;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#42b983}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#42b983}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="http://schema.org/Person"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><h3 class="author__name" itemprop="name">MrBird's Blog</h3><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__urls-wrapper"><button class="btn btn--inverse">Follow</button><ul class="author__urls social-icons"><li><a href="http://map.baidu.com/?newmap=1&s=s%26wd%3D%E7%A6%8F%E5%B7%9E%E5%B8%82%26c%3D300&from=alamap&tpl=mapcity" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;FuZhou,CN</a></li><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i>&nbsp;&nbsp;Love</a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-chain" aria-hidden="true"></i>&nbsp;&nbsp;FEBS</a></li><li><a href="/atom.xml" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-rss" aria-hidden="true"></i>&nbsp;&nbsp;RSS</a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i>&nbsp;&nbsp;Gitee</a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i>&nbsp;&nbsp;GitHub</a></li><li><a href="javascript:;" class="popup-trigger"><i class="fa fa-fw fa-search" aria-hidden="true"></i>&nbsp;&nbsp;Search</a></li></ul></div></div></div><script>var $urls=$(".author__urls").find("a");$urls.each(function(){var o=$(this);o.mouseenter(function(){o.css({color:"#414547"})}),o.mouseleave(function(){o.css({color:""})})})</script></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#ThreadPoolExecutor"><span class="nav-number">1.</span> <span class="nav-text">ThreadPoolExecutor</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关闭线程池"><span class="nav-number">2.</span> <span class="nav-text">关闭线程池</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4大拒绝策略"><span class="nav-number">3.</span> <span class="nav-text">4大拒绝策略</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#CallerRunsPolicy"><span class="nav-number">3.1.</span> <span class="nav-text">CallerRunsPolicy</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AbortPolicy"><span class="nav-number">3.2.</span> <span class="nav-text">AbortPolicy</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DiscardOldestPolicy"><span class="nav-number">3.3.</span> <span class="nav-text">DiscardOldestPolicy</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DiscardPolicy"><span class="nav-number">3.4.</span> <span class="nav-text">DiscardPolicy</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程池工厂方法"><span class="nav-number">4.</span> <span class="nav-text">线程池工厂方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#newFixedThreadPool"><span class="nav-number">4.1.</span> <span class="nav-text">newFixedThreadPool</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#newCachedThreadPool"><span class="nav-number">4.2.</span> <span class="nav-text">newCachedThreadPool</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#newSingleThreadExecutor"><span class="nav-number">4.3.</span> <span class="nav-text">newSingleThreadExecutor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#newScheduledThreadPool"><span class="nav-number">4.4.</span> <span class="nav-text">newScheduledThreadPool</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一些API的用法"><span class="nav-number">5.</span> <span class="nav-text">一些API的用法</span></a></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer" onselectstart="return!1"><div class="footer-inner"><div class="copyright">&copy; 2016 - <span itemprop="copyrightYear">2019</span>&nbsp;&nbsp; <span class="author" itemprop="copyrightHolder">MrBird</span>&nbsp;&nbsp;|<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>&nbsp;&nbsp;UV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span> &nbsp;&nbsp;PV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span></div></div></footer><div class="back-to-top"><span style="font-family:'Source Sans Pro','Helvetica Neue',Arial,sans-serif;font-size:1.2em;font-weight:600">TOP</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->